package com.leetcodehot.problems;

import java.util.ArrayList;
import java.util.List;

public class problems257 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 二叉树+回溯
     */
    private List<String> res;
    private List<String> temp;

    public List<String> binaryTreePaths(TreeNode root) {
        res = new ArrayList<>();
        temp = new ArrayList<>();
        dfs(root);
        return res;
    }

    private void dfs(TreeNode root) {
        temp.add(String.valueOf(root.val) + "->");
        if (root.left == null && root.right == null) {
            StringBuilder stringBuilder = new StringBuilder();
            for (String str : temp) {
                stringBuilder.append(str);
            }
            res.add(stringBuilder.substring(0, stringBuilder.length() - 2));
        }
        if (root.left != null) {
            dfs(root.left);
        }
        if (root.right != null) {
            dfs(root.right);
        }
        temp.remove(temp.size() - 1);
    }
}
